
var app = getApp();
var ApiUrl = app.globalData.ApiUrl;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    all_election_checked:false,
    total_limit:0,
    total_limit_num:0,
    shopping_cart_cainixihuan:[],
    shopping_cart_datalist:[
      // {
      //   id:1,
      //   imgUrl:'/image/1576139402426.jpg',
      //   title:'享安心鲜鸡蛋10枚（新老包装随机发货',
      //   min_title:'享安心鲜鸡蛋10枚',
      //   new_price:'7.9',
      //   old_price:'9.9',
      //   num:1,
      //   checked:true
      // },
      // {
      //   id: 2,
      //   imgUrl: '/image/1576139402426.jpg',
      //   title: '享安心鲜鸡蛋10枚（新老包装随机发货',
      //   min_title: '享安心鲜鸡蛋10枚',
      //   new_price: '7.9',
      //   old_price: '9.9',
      //   num: 1,
      //   checked: true
      // }
    ]
  
  },
  allCheckboxChange:function (e){//全选
    // if (that.data.shopping_cart_datalist.length == 0){
    //   this.setData({
    //     all_election_checked: false
    //   })
    //   alert("购物车为空");
    //   return;
    // }
    let all_election_checked = this.data.all_election_checked;
    if (all_election_checked) {
      this.setData({
        all_election_checked: false
      })
    } else {
      this.setData({
        all_election_checked: true
      })
    }
    this.selectall();//全部选中
//console.log(this.data.all_election_checked);
  },
  selectall: function () {//全部选中
    let that = this;
    for (let i = 0; i < that.data.shopping_cart_datalist.length; i++) {
      that.data.shopping_cart_datalist[i].checked = (that.data.all_election_checked)
    }

    that.setData({
      shopping_cart_datalist: that.data.shopping_cart_datalist,
      all_election_checked: (that.data.all_election_checked)
    })
    that.totalLimit();
  },
  checkboxChange: function (e) {//单个选中/不选
    let query = e.currentTarget.dataset['index'];
    let that = this;
//console.log(query);
    that.data.shopping_cart_datalist[query].checked = !that.data.shopping_cart_datalist[query].checked;
    var all_election_checked = that.data.all_election_checked;
    var n = 0;
    for (let i = 0; i < that.data.shopping_cart_datalist.length; i++) {
      if (that.data.shopping_cart_datalist[i].checked){
        n++;
      }
      if (n == that.data.shopping_cart_datalist.length) {
        that.setData({
          all_election_checked: true
        })
      } else {
        that.setData({
          all_election_checked: false
        })
      }
    }
    that.totalLimit();
  },
  bindMinus: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    let num = that.data.shopping_cart_datalist[index].goods_num;
    let n = that.data.shopping_cart_datalist.length;
    num--;
    if (num < 1) {
      that.dele_shopping_cart_list_data(that.data.shopping_cart_datalist[index].cart_id);
      n--;
      if(n == 0){
        that.data.all_election_checked = false;
      }
    }
    that.data.shopping_cart_datalist[index].goods_num = num;
    that.setData({
      shopping_cart_datalist: that.data.shopping_cart_datalist,
      all_election_checked: that.data.all_election_checked
    })
  

    that.cart_edit_quantity(id, num);
    that.totalLimit();
  },
  // index.php?act=member_cart&op=cart_edit_quantity
  cart_edit_quantity(id,num){
    let k = wx.getStorageSync('key');
    let that = this;
    console.log(id,num);
    wx.request({
      url: ApiUrl + "/index.php?act=member_cart&op=cart_edit_quantity",
      data: { key: k, cart_id: id, quantity:num },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success: function (result) {
        console.log(result);
        if (result.statusCode == 200) {
          if (result.data.code == 200) {
            that.add_shopping_cart_list_data();
          }
        }
      }
    })
  },
  bindPlus: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    let num = that.data.shopping_cart_datalist[index].goods_num;
    num++;
    that.data.shopping_cart_datalist[index].goods_num = num;
    that.setData({
      shopping_cart_datalist: that.data.shopping_cart_datalist
    })
    that.cart_edit_quantity(id, num);
    that.totalLimit();
  },
  totalLimit: function () {
    let that = this;
    let res = 0;
    that.data.total_limit_num = 0;
    for (let i = 0; i < that.data.shopping_cart_datalist.length; i++) {
//console.log(that.data.total_limit,1);
      if (that.data.shopping_cart_datalist[i].checked){
        let num = parseInt(that.data.shopping_cart_datalist[i].goods_num);
        let new_price = that.data.shopping_cart_datalist[i].goods_price;
        res += num * new_price;
        that.data.total_limit_num += num;

        wx.setStorageSync('total_limit_num', that.data.total_limit_num);
      }
    }
    res = res.toFixed(2);
    that.setData({
      total_limit: res,
      total_limit_num: that.data.total_limit_num
    })
    if (that.data.total_limit_num){
      wx.setTabBarBadge({//tabbar右上角添加文本
        index: 3, ////tabbar下标
        text: '' + that.data.total_limit_num	//显示的内容
      })
    }else{
      wx.removeTabBarBadge({
        index:3
      });
    }
    

  },
  deleteBtn() {//删除个数
    let that = this;
    let n = that.data.shopping_cart_datalist.length;
    for (let i = 0; i < that.data.shopping_cart_datalist.length; i++) {
      if (that.data.shopping_cart_datalist[i].checked) {
        that.dele_shopping_cart_list_data(that.data.shopping_cart_datalist[i].cart_id);
        n--;

        if (n > 0) {
          that.setData({
            all_election_checked: true
          })
//console.log('all_election_checked: true')
        } else {
          that.setData({
            all_election_checked: false
          })
//console.log('all_election_checked: false')
        }
      }
    }
  },
  orderList(){
    console.log(this.data.shopping_cart_datalist,'购物车即将跳转');
    let shopping_cart_datalist = this.data.shopping_cart_datalist;
    console.log(shopping_cart_datalist);

    wx.setStorageSync('shopping_cart_datalist', shopping_cart_datalist);
    wx.navigateTo({
      // url: '../../pages/order/order?shopping_cart_datalist=' + shopping_cart_datalist
      url: '../../pages/order/order'
    })
  },
  add_shopping_cart_list_data() {//获取购物车购买物品数据列表
    wx.showLoading({
      title: "加载中..."
    })
    let k = wx.getStorageSync('key'); 
    let that = this;
    wx.request({
      url: ApiUrl + "/index.php?act=member_cart&op=cart_list",
      data: { key: k },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success: function (result) {
//console.log(result);
        if (result.statusCode == 200){
          if (result.data.code == 200) {
            if (result.data.datas.cart_list.length) {
              let datas = result.data.datas.cart_list[0].goods;
              // let datas = result.data.datas.cart_list;

              wx.setStorageSync('shopping_cart_datalis', datas);

              let datas2 = wx.getStorageSync('shopping_cart_datalis');

console.log(datas2,9000);
//console.log(typeof datas2,900000);
              wx.hideLoading();
              that.data.shopping_cart_datalist = datas2;

              // that.data.shopping_cart_datalist = datas;
              that.data.all_election_checked = true;
            }else{
              that.data.shopping_cart_datalist = [];
              wx.hideLoading();
              wx.removeStorageSync('shopping_cart_datalis');
            }

            let n = 0;
            if (that.data.shopping_cart_datalist.length > 0) {
              for (let i = 0; i < that.data.shopping_cart_datalist.length; i++) {
                that.data.shopping_cart_datalist[i].checked = true;
                n+=parseFloat(that.data.shopping_cart_datalist[i].goods_num);
              }
            }

console.log(that.data.shopping_cart_datalist,9090909);
            that.setData({
              shopping_cart_datalist: that.data.shopping_cart_datalist,
              total_limit: result.data.datas.sum,
              total_limit_num: n,
              all_election_checked: that.data.all_election_checked 
            })
            console.log(result.data.datas.cart_count,80808080);

            if (result.data.datas.cart_count) {
              wx.setTabBarBadge({//tabbar右上角添加文本
                index: 3, ////tabbar下标
                text: '' + n	//显示的内容
              })
            } else {
              wx.removeTabBarBadge({
                index: 3
              })
            }
            wx.setStorageSync('total_limit_num', n);
          }
        }else{
          wx.hideLoading();
        }
      }
    })

  },
  dele_shopping_cart_list_data(id) {//删除购物车购买物品数据列表 
//console.log("删除购物车id:"+id);
    let k = wx.getStorageSync('key');
    let that = this;
    wx.request({
      url: ApiUrl + "/index.php?act=member_cart&op=cart_del",
      data: { key: k, cart_id:id},
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success: function (result) {
//console.log(result);
        if (result.statusCode == 200) {
          if (result.data.code == 200) {
//console.log(result.data.datas);
            that.add_shopping_cart_list_data();
          }
        }
      }
    })
  },

  //获取猜你喜欢
  //index.php?act=goods&op=goods_list
  addcainixihuan(){
    let that = this;
    wx.request({
      url: ApiUrl + "/index.php?act=goods&op=goods_list",
      data: {
        key:2, //排序方式 1-销量 2-浏览量 3-价格 空-按最新发布排序
        order:'',// 排序方式 1-升序 2-降序
        page:3, //每页数量
        curpage:1, // 当前页码
        gc_id:'',//分类编号
        keyword:'',// 搜索关键字
        barcode: '',//商品条形码
        b_id:'',// 品牌id
       // gc_id、keyword、barcode、b_id 四选一不能同时出现
        own_shop:'',// 是否自营 1是
        gift :'',//是否赠品 1是
        area_id:'',// 一级地区ID
        ci :'',//消保ID，多个消保时ID以英文下划线“_”分隔, 如 2_7_8
        groupbuy:'',// 是否是团购 1是
        xianshi :'',//是否是限时折扣 1是
        price_from:'',// 价格筛选下限
        price_to :''//价格筛选上限
      },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success: function (result) {
        //console.log(result);
        if (result.statusCode == 200) {
          if (result.data.code == 200) {
            console.log(result.data.datas.goods_list, 999111); 
            let res = result.data.datas.goods_list;
            that.setData({
              shopping_cart_cainixihuan:res
            })
          }
        }
      }
    })
  },
//添加购物车//index.php?act=member_cart&op=cart_batchadd
  add_cart_batchadd(strS) {
    let that = this;
    let k = wx.getStorageSync('key');
    wx.request({
      url: ApiUrl + "/index.php?act=member_cart&op=cart_batchadd",
      data: {
        key: k,
        cartlist: strS //新增购物列表，数据格式为goods_id1, num1| goods_id2, num2
      },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success: function (result) {
        //console.log(result);
        if (result.statusCode == 200) {
          if (result.data.code == 200) {
            console.log('添加购物车:=======>',result.data.datas);

            that.add_shopping_cart_list_data(); 
            let res = result.data.datas;
            // that.setData({
            //   shopping_cart_cainixihuan: res
            // })
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLaunch() {
    this.totalLimit();
  },
  onShow() {
    this.add_shopping_cart_list_data();
    let strS = app.globalData.community_id_for_switch_tab;
    console.log(strS);
    if (strS) {
      this.add_cart_batchadd(strS);
      app.globalData.community_id_for_switch_tab = null;
    }


    let num = wx.getStorageSync('total_limit_num');

    if (num) {
      wx.setTabBarBadge({//tabbar右上角添加文本
        index: 3, ////tabbar下标
        text: '' + num	//显示的内容
      })
    } else {
      wx.removeTabBarBadge({
        index: 3
      })
    }
  },
  onLoad: function (options) {
    let strS = app.globalData.community_id_for_switch_tab;
    console.log(strS);
    if (strS) {
      this.add_cart_batchadd(strS);
      app.globalData.community_id_for_switch_tab = null;
    }
    this.add_shopping_cart_list_data();
    this.addcainixihuan();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
//console.log('onReady');
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    wx.setStorageSync('total_limit_num', this.data.total_limit_num);
//console.log('onHide');
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
//console.log('onUnload');
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
//console.log('onPullDownRefresh');
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
//console.log('onReachBottom');
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
//console.log('onShareAppMessage');
  
  }
})